package com.api.qfengx.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.weaver.qfengx.*;
import com.weaver.qfengx.config.DevModeConfig;
import com.weaver.qfengx.entity.Result;
import okhttp3.Response;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.Map;

/**
 * 微信相关API
 */
@Path("/qfengx/wx/")
public class WxApi {

    private static final LogUtils log = new LogUtils(WxApi.class);

    private Response queryQyAccessToken(String appid, String secret) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("corpid", appid);
        params.put("corpsecret", secret);
        return RequestUtils.doGetWithoutChange("https://qyapi.weixin.qq.com/cgi-bin/gettoken", params);
    }

    private Response queryQyTicket(String token) throws IOException {
        // 获取ticket
        Map<String, String> params = Maps.newHashMap();
        params.put("access_token", token);
        return RequestUtils.doGetWithoutChange("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket", params);
    }

    private Result queryTicketResult() throws IOException {
        String appid = DevModeConfig.getPropConfig("wx.qyAppid", PropUtils.get("WeaverUtilsConfig", "wx.qyAppid", "")).getValue();
        String secret = DevModeConfig.getPropConfig("wx.qyAppSecret", PropUtils.get("WeaverUtilsConfig", "wx.qyAppSecret", "")).getValue();
        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(secret)) {
            return Result.fail("appid或secret未配置");
        }
        Response response = queryQyAccessToken(appid, secret);
        if (response.isSuccessful()) {
            String body = response.body().string();
            JSONObject obj = JSONObject.parseObject(body);
            int errcode = obj.getInteger("errcode");
            if (errcode == 0) {
                String token = obj.getString("access_token");
                // 获取ticket
                log.writeLog("获取ticket, appid => " + appid + ", secret => " + secret + ", token => " + token);
                Response ticketResp = queryQyTicket(token);
                if (ticketResp.isSuccessful()) {
                    String tbody = ticketResp.body().string();
                    JSONObject tobj = JSONObject.parseObject(tbody);
                    int tErrcode = tobj.getInteger("errcode");
                    if (tErrcode == 0) {
                        return Result.ok(tobj.getString("ticket"));
                    } else {
                        return Result.fail("获取ticket失败: " + tobj.getString("errmsg"));
                    }
                } else {
                    return Result.fail("ticket请求错误: " + ticketResp.code());
                }
            } else {
                return Result.fail("获取AccessToken失败：" + obj.getString("errmsg"));
            }
        } else {
            return Result.fail("请求错误: " + response.code());
        }
    }

    @POST
    @Path("/qyTicket")
    @Produces(MediaType.APPLICATION_JSON)
    public String qyTicket(@Context HttpServletRequest request,
                           @Context HttpServletResponse response) throws IOException {
        return JSON.toJSONString(queryTicketResult());
    }

    @POST
    @Path("/qySignature")
    @Produces(MediaType.APPLICATION_JSON)
    public String qySignature(@Context HttpServletRequest request,
                              @Context HttpServletResponse response) throws IOException {
        String url = request.getParameter("url");
        Result tikcetRes = queryTicketResult();
        if (tikcetRes.isOk()) {
            String noncestr = StringUtils.random(16);
            long timestamp = System.currentTimeMillis() / 1000;
            String jsapi_ticket = StringUtils.val(tikcetRes.getData());
            String str1 = String.format("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", jsapi_ticket, noncestr, timestamp, url);
            log.writeLog("获取签名信息 => str1 ==> " + str1);
            String sha1 = CryptUtils.sha1(str1);
            Map<String, Object> map = Maps.newHashMap();
            map.put("noncestr", noncestr);
            map.put("timestamp", timestamp);
            map.put("signature", sha1);
            return JSON.toJSONString(Result.ok(map));
        } else {
            return JSON.toJSONString(tikcetRes);
        }
    }


}
